package net.blogways.ordermgr.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;


import com.asiainfo.bpc.utils.ToolFactory;
import org.apache.commons.chain.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author wanghui
 *         Created on 2017/10/30.
 */
public class DBTools {

  private static final Logger log = (Logger) LoggerFactory.getLogger(DBTools.class);

  private static final String REGEX_QUANTITY = "^[1-9]\\d*$";

  private static final String REGEX_PRICE = "\\d\\.\\d*|[1-9]\\d*|\\d*\\.\\d*|\\d";

  private static final Long REGEX_MAX_NUM = 99999999999L;

  public static Map parameterize(Map params) {
    Map result = new HashMap();
    if (params.keySet().size() > 0) {
      params.forEach((k, v) -> {
        if (k instanceof String) {
          result.put("V" + k, v);
        }
      });
    }
    return result;
  }

  /**
   * 获取数据库当前时间
   * @return
   */
  public static String queryCurrentTime() throws ExecutionException {

   Map<String, Object> result = (Map<String, Object>) ToolFactory.getInstance().getSqlCodeService()
           .select(Constants.CURRENT_TIME, Constants.DUAL, new HashMap<>()).get(0);
   return result.get("NOW").toString();

  }

  /**
   * 校验是否存在后置流程.
   * @param context
   */
  public static void checkBeforeEnd(Context context) {

    Map<String, Object> base = (Map<String, Object>) context.get("Base");

    if (base.containsKey("FOLLOWUP_LCU")
            && base.get("FOLLOWUP_LCU") != null
            && !context.containsKey("followUpChain")) {
      context.put("followUpChain", base.get("FOLLOWUP_LCU"));
      base.remove("FOLLOWUP_LCU");
    }

    if (base.containsKey("pks")) {
      base.remove("pks");
    }

  }

  /**
   * 查询唯一数据.
   * @param ref
   * @param table
   * @param dbRoute
   * @param params
   * @return
   * @throws ExecutionException
   */
  public static Map selectOne(String ref, String table, String dbRoute,  Map<String, Object> params)
          throws ExecutionException {

    log.debug("selectOne begin :***************, ref = {}, table = {}", ref, table);

    if ("TF_B_SUBSCRIBE_BATDEAL".equals(table) || "TD_S_COMMPARA".equals(table)) {
      dbRoute = Constants.DATABASE_CEN;
    }

    log.debug("dbRoute = {}, param = {}", dbRoute, params);
    List retList = ToolFactory.getInstance().getSqlCodeService(dbRoute).select(ref, table, params);

    log.debug("params = {}", params.toString());
    log.debug("ref = {}", ref);
    log.debug("table = {}", table);
    log.debug("retList = {}", retList);
    if (retList.size() == 0){
      log.debug("No Record!!!!");
      log.debug("selectOne end :***************");
      return new HashMap<String, Object>();
    }
    log.debug("selectOne end :***************");
    return new HashMap<String, Object>() {
      {
        put("resultSize", retList.size());
        put("resultOne", retList.get(0));
      }
    };
  }

  /**
   * 防止sql注入.
   *
   * @param str
   * @return
   */
  public static boolean sql(String str) throws Exception {
    String reg = "(?i).*('|and\\s|exec\\s|execute\\s|insert\\s|select\\s|delete\\s|update\\s|count\\s|drop\\s|"+
            "\"|\\$|\\||<|>|&|%|,|;|--|//|/|#|@|\\+|\\*|\\(|\\)|\\\"|\\\\|"+
            "char\\s|declare\\s|sitename\\s|net user\\s|xp_cmdshell\\s|like'|create\\s|" +
            "table\\s|from\\s|grant\\s|use\\s|group_concat\\s|column_name\\s|" +
            "information_schema\\.columns|table_schema\\s|union\\s|where\\s|by\\s|" +
            "chr\\s|mid\\s|master\\s|truncate\\s|or\\s+|like\\s|\\n|\\r).*";
    if (str.matches(reg)) {
      log.debug("SQL DOES NOT MATCHES"+str);
      return false;
    }
    return true;
  }

  /**
   * 数量校验.
   * @return
   */
  public static boolean checkQuantity(String num){

    if (Pattern.matches(REGEX_QUANTITY, num)){
      if (Long.compare(Long.valueOf(num), REGEX_MAX_NUM) != 1){
        return true;
      }
    }
    return false;
  }

  /**
   * 价格校验.
   * @param price
   * @return
   */
  public static boolean checkPrice(String price){
    return Pattern.matches(REGEX_PRICE, price);
  }


}
